import os

import pymysql

from config import DIR_PATH
import json, yaml
import logging.handlers
from bs4 import BeautifulSoup


def read_json(file_name, key):
    file_path = DIR_PATH + os.sep + 'data' + os.sep + file_name
    arr = []
    with open(file_path, 'r', encoding='utf-8') as f:
        for data in json.load(f).get(key):
            arr.append(tuple(data.values())[1:])
    return arr


def read_yaml(file_name, key):
    file_path = DIR_PATH + os.sep + 'data' + os.sep + file_name
    arr = []
    print(key)
    with open(file_path, 'r', encoding='utf-8') as f:
        for data in yaml.safe_load(f).get(key):
            arr.append(tuple(data.values())[1:])
    return arr


class GetLog:
    __logger = None

    @classmethod
    def get_logger(cls):
        if cls.__logger is None:
            # 获取日志器
            cls.__logger = logging.getLogger()
            # 设置日志级别
            cls.__logger.setLevel(logging.INFO)
            filepath = DIR_PATH + os.sep + 'log' + os.sep + 'p2p.log'
            # 获取处理器
            tf = logging.handlers.TimedRotatingFileHandler(filename=filepath,
                                                           when="midnight",
                                                           interval=1,
                                                           backupCount=3,
                                                           encoding='utf-8')
            fmt = '%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s'
            # 设置格式器
            fm = logging.Formatter(fmt)
            # 格式器添加到处理器
            tf.setFormatter(fm)
            # 处理器添加到日志器
            cls.__logger.addHandler(tf)
        return cls.__logger


def html_parser(result):
    html = result.json()['description'].get('form')
    bs = BeautifulSoup(html, 'html.parser')
    url = bs.form.get('action')
    data = {}
    for input in bs.findAll('input'):
        data[input.get('name')] = input.get('value')
    return url, data


def conn_sql(sql):
    try:
        conn = pymysql.connect(host='', port='', user='', password='', database='', charset='utf8')
        cursor = conn.cursor()
        cursor.execute(sql)
    except Exception as e:
        GetLog.get_logger().error(e)
        raise
    finally:
        cursor.close()
        conn.close()